/* $RCSFile: AddonNicePanes.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/UI/WebControls/AddonNicePanes.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:29  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using System.ComponentModel;
using System.Globalization;
using System.Configuration;
using System.Collections;
using System.Threading;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;

using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.Settings;
using AddonNice.Configuration;
using AddonNice.Diagnostics;

using Trace2    =   System.Diagnostics.Trace;
using Path2     =   AddonNice.Settings.Path;

namespace AddonNice.UI.WebControls
{
    /// <summary>
    /// This class is doing all the loading for PortalModulControls and placing them in correct panes according data from DB
    /// </summary>
	public class AddonNicePanes : AddonNicePanesBase
	{
		/// <summary>
		/// This method determines the tab index of the currently
		/// requested portal view, and then dynamically populate the left,
		/// center and right hand sections of the portal tab.
		///  </summary>
		protected override ArrayList[] InitializeDataSource()
		{
            if ( PanesTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]AddonNicePanes InitializeDataSource BEG.",PanesTraceSwitch.Sw.Info);

			ArrayList[] DS                      =    base.InitializeDataSource();
            if ( DesignMode )
                return DS;

			// Obtain PortalSettings from Current Context
			PortalSettings portalSettings       =   (PortalSettings) HttpContext.Current.Items[StStr.strPortalSettings];
            int mCache                          =   Config.ModuleOverrideCache;
            
			// Dynamically populates the Left, Center and Right pane sections of the portal page
			// Loop through each entry in the configuration system for this page
            ModulesDB mDB                       =   new ModulesDB();
            string  portalCulture               =   portalSettings.PortalContentLanguage.Name + ";";
            if ( SecurityTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddonNicePanes InitializeDataSource portalCulture: {0}, portalSettings.ActivePageSettings.Modules.Count: {1}", portalCulture,portalSettings.ActivePageSettings.Modules.Count),SecurityTraceSwitch.Sw.Info);
            for (int i=0 ; i < portalSettings.ActivePageSettings.Modules.Count ; i++ )
            {
                ModuleConfiguration _moduleSettings = portalSettings.ActivePageSettings.Modules[i];
                
                // Is this module allowed for current portal language
                string mdCultures               =   mDB.GetSingleSettings(_moduleSettings.ModuleID,StStr.ModuleSettingsCulture).Trim(new char[]{';'});
                if ( mdCultures != string.Empty && (mdCultures + ";").IndexOf(portalCulture) <= 0)
                {
                    if ( PanesTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddonNicePanes InitializeDataSource Module not allowed for this language ID : {0}, Culture: {1}, portalCulture: {2}", _moduleSettings.ModuleID,mdCultures,portalCulture),PanesTraceSwitch.Sw.Info);
                    continue;
                }
 
                if (!_moduleSettings.Cacheable)
                    _moduleSettings.CacheTime   =   -1; // Disable cache
                if ( SecurityTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddonNicePanes InitializeDataSource ModuleID: {0}, AuthorizedViewRoles: {1}", _moduleSettings.ModuleID,_moduleSettings.AuthorizedViewRoles),SecurityTraceSwitch.Sw.Info);

                if (PortalSecurity.IsUserInRoles(_moduleSettings.AuthorizedViewRoles))
                {
                    ArrayList arrayData;

                    switch (_moduleSettings.PaneName.ToLower())
                    {
                        case StStr.leftPane:
                            arrayData           =   DS[IDX_LEFT_PANE_DATA];
                            break;
                        case StStr.rightPane:
                            arrayData           =   DS[IDX_RIGHT_PANE_DATA];
                            break;
                        case StStr.contentPane:
                        default:
                            arrayData           =   DS[IDX_CONTENT_PANE_DATA];
                            break;
                    }

                    // If no caching is specified, create the user control instance and dynamically
                    // inject it into the page.  Otherwise, create a cached module instance that
                    // may or may not optionally inject the module into the tree

                    //Cache. If == 0 then override with default cache in web.config
                    if (!_moduleSettings.Admin && _moduleSettings.CacheTime == 0 && mCache > 0 )
                            _moduleSettings.CacheTime = mCache;

                    // a user who has edit or properties permission will not cause the module output to be cached. 
                    if (
                        ( _moduleSettings.CacheTime <= 0 )
                        || PortalSecurity.IsUserInRoles(_moduleSettings.AuthorizedEditRoles)
                        || PortalSecurity.IsUserInRoles(_moduleSettings.AuthorizedPropertiesRoles)
                        || PortalSecurity.IsUserInRoles(_moduleSettings.AuthorizedAddRoles)
                        || PortalSecurity.IsUserInRoles(_moduleSettings.AuthorizedDeleteRoles)
                        )
                    {
                        string controlPath      =   Path2.WebPathCombine(Path2.ApplicationRoot, _moduleSettings.DesktopSrc);
                        if ( PanesTraceSwitch.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddonNicePanes InitializeDataSource LoadControl: {0}.", controlPath),PanesTraceSwitch.Sw.Info);
                        PortalModuleControl portalModule    =   null;
                        try
                        {
                            portalModule        =   ((ADNPage)Page).LoadPortalModule(controlPath,portalSettings.PortalID,_moduleSettings,false);
                            arrayData.Add(portalModule);
                        }
                        catch (ThreadAbortException tex) // Let a place for a module redirecting from its ctor
                        {
                            if ( PanesTraceSwitch.Sw.TraceError )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]AddonNicePanes InitializeDataSource Thread aborted loading control {0}, ex: {1}", _moduleSettings.DesktopSrc, tex),PanesTraceSwitch.Sw.Info);
                            throw;
                        }
                        catch (Exception ex)
                        {
                            if ( PanesTraceSwitch.Sw.TraceError )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]AddonNicePanes InitializeDataSource Unable to load control {0}, ex: {1}", _moduleSettings.DesktopSrc, ex),PanesTraceSwitch.Sw.Info);
                        }
                    }
                    else
                    {
                        if ( PanesTraceSwitch.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddonNicePanes InitializeDataSource Module loaded from cache ID : {0}, CacheTime: {1}", _moduleSettings.ModuleID,_moduleSettings.CacheTime),PanesTraceSwitch.Sw.Info);
                        try
                        {
                            CachedPortalModuleControl portalModule  = new CachedPortalModuleControl();
                            portalModule.PortalID                   = portalSettings.PortalID;
                            portalModule.ModuleConfiguration        = _moduleSettings;
                            arrayData.Add(portalModule);
                        }
                        catch (Exception ex)
                        {
                            if ( PanesTraceSwitch.Sw.TraceError )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]AddonNicePanes InitializeDataSource Unable to load cached control {0}, ex: {1}", _moduleSettings.DesktopSrc, ex),PanesTraceSwitch.Sw.Info);
                        }
                    }
                }
            }
         if ( PanesTraceSwitch.Sw.TraceVerbose )
            Trace2.WriteLine( "[V]AddonNicePanes InitializeDataSource END.",PanesTraceSwitch.Sw.Info);
         return DS;
		}
	}
}